<?php
/** 
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20210822
 * Time: 11:05 
 * 当冲管理
 */
namespace app\api\controller;

use  Mscore\Core\Controller;
use  app\api\model\Dueltrade as DueltradeModel;
use  app\api\model\Common as CommonModel;
use  app\api\model\Login as LoginModel;
use  Mscore\Core\Util\Util;
use  Mscore\Core\Util\Xcode;
use  Mscore\Core\Lang;

class DueltradeController extends Controller{

    private $model;
    private $login;
    private $error;
    private $success;

    /**
     * 初始化自动连接方法
     * @param array $__construct 
     * @param array $where 
    */
    public function __construct()  
    {    
        $this->model = new DueltradeModel;
        $this->login = (new LoginModel)->isAuth();
        $this->header =get_all_headers();
        $this->header['language']=isset($this->header['language'])&&!empty($this->header['language'])?$this->header['language']:config('langs.default');
        Lang::init($this->header['language']);
        $this->success=Lang::get('Success');
        $this->error=Lang::get('Error');
        $this->controls = config('duelcontrol','/config/duel');unset($this->controls['duelcontrol']);
    }

    /**
     * 产品类别列表
     * @param array $catelist 
     * @param array $where 
     */ 
    public function catelist(){
        $pro=[];
        switch (true) {
            case !empty(post('id')):
                $where = 'a.id='.post('id');
                $pro = $this->model->catelist($where);
                $this->success['data']=$pro['data'];
                $this->success['count']=$pro['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = 'a.dels<1';
                $pro = $this->model->catelist($where,$page,$limit);
                $this->success['data']=$pro['data'];
                $this->success['count']=$pro['total'];
                return $this->echojson($this->success);
                break;
        } 
    }

    /**
     * 产品列表
     * @param array $dueltrade 
     * @param array $where 
     */ 
    public function dueltrade(){
        $pro=[];
        switch (true) {
            case !empty(post('id')):
                $where = 'a.id='.post('id');
                $pro = $this->model->dueltrade($where);
                if(!empty($pro['data'][0]['titles'])){
                    $pro['data'][0]['title']=isset(json_decode($pro['data'][0]['titles'],true)[$this->header['language']])?json_decode($pro['data'][0]['titles'],true)[$this->header['language']]:$pro['data'][0]['title'];
                    unset($pro['data'][0]['titles']);
                }
                if(isset($pro['data'][0]['online'])&&!empty($pro['data'][0]['online'])){
                    $online=explode(",", $value['online']);
                    $pro['data'][0]['online']=rand($online[0],$online[1]);
                }else{
                    $pro['data'][0]['online']=0;
                }
                $this->success['data']=$pro['data'];
                $this->success['count']=$pro['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = 'a.dels<1 and a.status<3';
                if(!empty(post('cid'))){
                    $where .= ' and a.cid='.post('cid');
                }
                if(!empty(post('keyworld'))){
                    $where .= ' and ( a.title like "%'.post('keyworld').'%" or a.procode like "%'.post('keyworld').'%" ) ';
                }
                $pro = $this->model->dueltrade($where,$page,$limit);
                foreach ($pro['data'] as $key => $value) {
                    if(!empty($value['titles'])){
                        $pro['data'][$key]['title']=isset(json_decode($value['titles'],true)[$this->header['language']])?json_decode($value['titles'],true)[$this->header['language']]:$value['title'];  
                    }
                    if(isset($value['imgurl'])&&!empty($value['imgurl'])){
                        $pro['data'][$key]['imgurl']=config('file.baseurl').$value['imgurl'];
                    }
                    if(isset($value['online'])&&!empty($value['online'])){
                        $online=explode("-", $value['online']);
                        $pro['data'][$key]['online']=rand($online[0],$online[1]);
                    }else{
                        $pro['data'][$key]['online']=0;
                    }
                    $pro['data'][$key]['win']=$this->model->duelrisklog('proid='.$value['id'],'win,createtime');
                    unset($pro['data'][$key]['titles']);
                }
                $this->success['data']=$pro['data'];
                $this->success['count']=$pro['total'];
                return $this->echojson($this->success);
                break;
        } 
    }

    /**
     * 当冲产品详情
     * @param array $dueltradeinfo 
     * @param array $where 
    */ 
    public function dueltradeinfo(){
        $id=post('id',false);
        switch (true) {
            case $id>0:
                $where = ' id='.$id;
                $pro = $this->model->dueltradeinfo($where);
                if(!empty($pro['titles'])){
                    $pro['title']=isset(json_decode($pro['titles'],true)[$this->header['language']])?json_decode($pro['titles'],true)[$this->header['language']]:$pro['title'];
                    unset($pro['titles']);
                }
                if(!isset($pro['id'])){
                    return $this->echojson($this->error);
                }
                if(isset($pro['imgurl'])&&!empty($pro['imgurl'])){
                    $pro['imgurl']=config('file.baseurl').$pro['imgurl'];
                }
                $info = $this->model->operateinfo(' aid='.$this->login['pid'].' and proid='.$pro['id'].' and dels<1 and status=1','aid,auto,relate,fixmoney,fixtime');
                if(empty($info)){
                    $info = $this->model->operateinfo(' proid='.$pro['id'].' and dels<1 and status=1','aid,auto,relate,fixmoney,fixtime'); //獲取平台控制
                }
                //获取运营参数
                $duelc= $this->controls;
                $operate=$this->model->execRedis('get',[$duelc['key']]);
                $operate=json_decode($operate,true);
                if(!empty($operate)){
                    $fee = (new CommonModel())->getBaseinfo('keyname="duelcontrol"','content')['content'];
                    $pro['sn']=$operate['acode'];
                    $pro['fixmoney']=!empty($info['fixmoney'])?$info['fixmoney']:$operate['fixmoney'];
                    $pro['fee']=!empty($fee['fee'])?floatval($fee['fee']):10;
                    $pro['timelong']=$operate['timelong'];
                    $pro['endtime']=$operate['endtime'];
                    $pro['fshow']=$duelc['fshow'];
                    $pro['settletime']=$operate['settletime'];
                }
                $this->success['data']=$pro;
                $this->success['count']=1;
                return $this->echojson($this->success);
                break;
            default:
                return $this->echojson($this->error);
                break;
        }
    }
    /**
     * 订单list
     * @param array $orderlist 
     * @param array $where 
     */ 
    public function orderlist(){
        switch (true) {
            case !empty(post('id')):
                $where = 'id='.post('id');
                $datalist = $this->model->list($where);
                $this->success['data']=$datalist['data'];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = ' dels<1 and aid = '.$this->login['aid'].' and status>1';
                if(post('time')){
                	$time=post('time');
                	switch ($time){
                    	case 1:
                        	$where .= '';
                        	break;
                    	case 2:
                        	$where .= " and (createtime BETWEEN CONCAT(CURDATE(),' 00:00:00') AND CONCAT(CURDATE(),' 23:59:59')) ";
                        	break;
                    	case 3:
                        	$where .= ' and (TO_DAYS(NOW()) - TO_DAYS(createtime) = 1)';
                        	break;
                    	case 4:
                        	$where .= ' and (WEEK(createtime) = WEEK(CURDATE()))';
                        	break;
                    	case 5:
                        	$where .= " and DATE_FORMAT(createtime,'%Y-%m')= DATE_FORMAT(CURDATE(),'%Y-%m')";
                        	break;
                    	case 6:
                        	$where .= " and (PERIOD_DIFF(DATE_FORMAT(NOW(),'%Y%m'),DATE_FORMAT(createtime,'%Y%m')) = 1)";
                        	break;
                    	default:
                        	return $this->echojson($this->error);
                        	break;
                	}
                    
                }
                $datalist = $this->model->list($where,$page,$limit);
                $this->success['data']=!empty($datalist['data'])?$datalist['data']:[];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
        } 
    }

    /**
     * 获取参数
     * @param array $getconfshow 
     * @param array $where 
     */ 
    public function getconfshow(){
        $duelcontrol=(new CommonModel())->getBaseinfo('keyname="duelcontrol"','content');
        $duelcontrol=!empty($duelcontrol)?$duelcontrol['content']:$this->controls;
        $this->success['data']=$duelcontrol;
        return $this->echojson($this->success); 
    }

    /**
     * 订单list
     * @param array $orderlistrun 
     * @param array $where 
     */ 
    public function orderlistrun(){
        switch (true) {
            case !empty(post('id')):
                $where = 'id='.post('id');
                $datalist = $this->model->list($where);
                $this->success['data']=$datalist['data'];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = ' dels<1 and aid = '.$this->login['aid'].' and status<2 ';
                if(post('proname')){
                    $where .= ' and proname like "%'.post('proname').'%"';
                }
                $datalist = $this->model->list($where,$page,$limit);
                $this->success['data']=!empty($datalist['data'])?$datalist['data']:[];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
        } 
    }

    /**
     * 订单orderadd
     * @param array $orderadd 
     * @param array $where 
     */ 
    public function orderadd(){
        $params = post();
        //判斷參數是否存在
        if(empty($params['proid'])) return $this->echoJson(Lang::get('Proempty'));
        if(empty($params['updown'])) return $this->echoJson(Lang::get('Updown'));
        //判斷用户id
        if(empty($this->login['aid'])) return $this->echoJson(Lang::get('Getusererror'));
        $user=(new CommonModel())->getAccount('aid='.$this->login['aid'],['aid','username','amount','giftamount','pid','paypwd','header_url','type']);
        $control=(new CommonModel())->getBaseinfo('keyname="duelcontrol"','content');
        $control=!empty($control)?$control['content']:$this->controls;
        //判斷支付密碼及驗證
        if($control['addorder']==1){
            if(empty($params['paypassword'])) return $this->echoJson(Lang::get('Paypwdempty'));
            if(empty($user['paypwd'])) return $this->echoJson(Lang::get('Paypwdset'));
            if (!Util::passwordVerify($params['paypassword'], $user['paypwd'])) return $this->echojson(Lang::get('Paypwderror'));
        }
        //初始化输赢参数
        $win=0;
        $pro = $this->model->dueltradeinfo('id='.$params['proid'],['id','title','titles','procode']);
        if(empty($pro)){$this->echoJson(Lang::get('Proempty'));}
        $key = $this->controls['key'];
        $operate=$this->model->execRedis('get',[$key]);
        if(empty($operate)){ $this->echoJson(Lang::get('Proempty'));}
        $operate=json_decode($operate,true);
        if(($operate['endtime']-time())<$operate['settletime']){
            return $this->echoJson(Lang::get('Ordertime'));
        }
        //判断其他参数
        if($control['moneytype']==1){
           if($user['amount']<$params['orderprice']) return $this->echoJson(Lang::get('Amountfew'));  //用戶金額
        }elseif($control['moneytype']==2){
           if($user['giftamount']<$params['orderprice']) return $this->echoJson(Lang::get('Amountfew')); //虛擬金額
        }
        //获取買入价
        $price = $this->model->getprice($pro['procode']);
        if(!isset($price['price'])&&empty($price['price'])){
            return $this->echojson(Lang::get('Ordererror'));
        }
        //算单
        $params=[
            'order_no'=>getNumID(6,'order',1),//年月日加8位计数,order文件计数名称，1代表类别，1订单
            'type'=>$control['moneytype'],
            'aid'=>$user['aid'],
            'pid'=>$user['pid'],
            'sn'=>$operate['acode'],
            'proid'=>$pro['id'],
            'proname'=>$pro['title'],
            'titles'=>$pro['titles'],
            'procode'=>$pro['procode'],
            'money'=>$params['orderprice'],
            'endtime'=>$operate['endtime'], 
            'updown'=>$params['updown'],
            'win'=>$win,
            'buyprice'=>$price['price'][0],
            'status'=>1,
            'createtime'=>date('Y-m-d H:i:s',time())
        ];
        (new CommonModel())->startTrans();
        try {
        	if($params['type']==1){
            	$money=($user['amount']-$params['money']);
            	$info = (new CommonModel())->updateAccount('aid='.$user['aid'],['amount'=>$money]);
        	}elseif($params['type']==2){
            	$money=($user['giftamount']-$params['money']);
            	$info = (new CommonModel())->updateAccount('aid='.$user['aid'],['giftamount'=>$money]);
        	}
        	$id=$this->model->addorder($params);
        	if($id){
                $data=[
                	'orderid'=>$id,
                    'sn'=>$operate['acode'],
                    'type'=>$params['type'],
                	'proid'=>$pro['id'],
                	'amount'=>$user['amount'],
                	'money'=>$params['money'],
                    'win'=>$win,
                	'createtime'=>time()
                ];
                $this->model->addorderlog($data);
            }
        	(new CommonModel())->commit();
            unset($data['win'],$data['sn']);
            $key=$this->controls['order'];
            $order=$this->model->execRedis('hget',[$key,$params['sn'].$params['procode']]); $order = !empty($order)?json_decode($order,true):[];
            $name=$params['updown']==2?'buyup':'buydown';
            $data['buyprice']=$params['buyprice'];$data['sellprice']=0;$data['type']=$user['type'];$data['username']=$user['username'];$data['utype']=$user['type'];
            $data['aid']=$user['aid'];$data['headerurl']=!empty($user['header_url'])&&file_exists(config('file.path').$user['header_url'])?config('file.baseurl').$user['header_url']:'';
            if($name=='buyup'){
                if(!isset($order['buyupnum'])){ $order['buyupnum']=0; }
                $order['buyupnum']=$order['buyupnum']+1;
            }else{
                if(!isset($order['buydownnum'])){ $order['buydownnum']=0; }
                $order['buydownnum']=$order['buydownnum']+1;
            }
            $order[$name][$data['orderid']]=$data;
            $this->model->execRedis('hset',[$key,$params['sn'].$params['procode'],json_encode($order,JSON_UNESCAPED_SLASHES)]);
        	return $this->echojson($this->success);
        } catch (Exception $e) {
        	(new CommonModel())->rollback();
        	return $this->echojson(Lang::get('Parerror'));
        }
    }

    /**
     * 订单结算settleorder
     * @param array $settleorder 
     * @param array $where 
     */ 
    public function settleorder(){
        $params = post();
        //判斷參數是否存在
        if(empty($params['sn'])) return $this->echoJson(Lang::get('Proempty'));
        //判斷用户id
        if(empty($this->login['aid'])) return $this->echoJson(Lang::get('Getusererror'));
        //获取订单
        $order = $this->model->orderinfo('sn='.$params['sn'].' and aid='.$this->login['aid'].' and proid='.$params['proid'].' and status>1','sum(winmoney) as winmoney, sum(money) as money');
        $winst = ($order['winmoney']-$order['money']);
        switch (true) {
        	case $winst>0:
        		$order['win']=1;
        		break;
        	case $winst<0:
        		$order['win']=2;
        		break;
        	default:
        		$order['win']=0;
        		break;
        }
        $this->success['data'] = $order;
        return $this->echojson($this->success);
    }
  
}
